﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FastFoodToNight.Models;
using System.Web.Mvc;

namespace FastFoodToNight
{
    public class _ShopCart:Controller
    {
        QLFOODContext db = new QLFOODContext();
        string ShoppingCartId { get; set; }
        public const string CartSessionKey = "masanpham";
        public static _ShopCart GetCart(HttpContextBase context)
        {
            var cart = new _ShopCart();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] =context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();
                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }

        public static _ShopCart GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        }
        public void AddToCart(SanPham sanpham)
        {
            // Get the matching cart and album instances
            var cartItem = db.CartItems.SingleOrDefault(c => c.masanpham.ToString() == ShoppingCartId);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem =new CartItem()
                {
                    masanpham =Convert.ToInt32( ShoppingCartId),
                    tensanpham=sanpham.tensanpham,
                    soluong = 1,
                    DateCreated = DateTime.Now
                };
                db.CartItems.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart, 
                // then add one to the quantity
                cartItem.soluong++;
            }
            // Save changes
            db.SaveChanges();
        }
        public int RemoveFromCart(int id)
        {
            // Get the cart
            var cartItem = db.CartItems.Single(
                cart =>  cart.masanpham == id);

            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.soluong> 1)
                {
                    cartItem.soluong--;
                    itemCount = cartItem.soluong;
                }
                else
                {
                    db.CartItems.Remove(cartItem);
                }
                // Save changes
                db.SaveChanges();
            }
            return itemCount;
        }
        public void EmptyCart()
        {
            var cartItems = db.CartItems.Where( cart => cart.masanpham==Convert.ToInt32( ShoppingCartId));

            foreach (var cartItem in cartItems)
            {
                db.CartItems.Remove(cartItem);
            }
            // Save changes
            db.SaveChanges();
        }
        public List<CartItem> GetCartItems()
        {
            var cs= db.CartItems.Where(p => p.masanpham ==Convert.ToInt32( ShoppingCartId));
            return cs.ToList();
        }
        public int GetCount()
        {
            // Get the count of each item in the cart and sum them up
            int? count = (from cartItems in db.CartItems
                          where cartItems.masanpham==Convert.ToInt32( ShoppingCartId)
                          select (int?)cartItems.soluong).Sum();
            // Return 0 if all entries are null
            return count ?? 0;
        }
        public decimal GetTotal()
        {
            // Multiply album price by count of that album to get 
            // the current price for each of those albums in the cart
            // sum all album price totals to get the cart total
            decimal? total = (from cartItems in db.CartItems
                              where cartItems.masanpham == Convert.ToInt32(ShoppingCartId)
                              select (int?)cartItems.soluong *cartItems.dongia).Sum();

            return total ?? decimal.Zero;
        }
        public int CreateOrder(HoaDon order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();
            // Iterate over the items in the cart, 
            // adding the order details for each
            foreach (var item in cartItems)
            {
                var orderDetail = new ChiTietDDH
                {
                    masanpham=item.masanpham,
                    soluong=item.soluong
                    
                    
                    //AlbumId = item.AlbumId,
                    //OrderId = order.OrderId,
                    //UnitPrice = item.Album.Price,
                    //Quantity = item.Count
                };
                // Set the order total of the shopping cart
                orderTotal += (item.soluong *Convert.ToDecimal( item.dongia));

                db.ChiTietDDHs.Add(orderDetail);

            }
            // Set the order's total to the orderTotal count
            order.tongtien =Convert.ToDouble( orderTotal);

            // Save the order
            db.SaveChanges();
            // Empty the shopping cart
            EmptyCart();
            // Return the OrderId as the confirmation number
            return order.mahoadon;
        }

    }
}